package com.tbit.uqbike.tergateway.wa206pkg;


import com.alibaba.fastjson.annotation.JSONField;
import com.tbit.uqbike.protocol.ATerPkg;
import com.tbit.uqbike.protocol.AnalyzeImpl.AAutoProtocol;
import com.tbit.uqbike.protocol.AnalyzeImpl.AProtocol;
import com.tbit.uqbike.protocol.AnalyzeImpl.WA206DeEnCoder;
import com.tbit.uqbike.tergateway.data.TerGatewayData;
import com.tbit.uqbike.tergateway.entity.AConnInfo;
import com.tbit.uqbike.tergateway.entity.TerTempData;
import io.netty.buffer.ByteBuf;

/**
 * Created by MyWin on 2017/4/27.
 */
public class SyncParam extends ATerPkg {

    private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SyncParam.class);

    @JSONField(name = "时间戳")
    public int syncTick;

    @Override
    public String toString() {
        return "SyncParam{" +
                "signPkg='" + signPkg + '\'' +
                ", mno='" + mno + '\'' +
                ", head=" + head +
                ", syncTick=" + syncTick +
                '}';
    }

    @Override
    public void doBusiness() {
        logger.debug(this.toString());
        try {
            int syncTime = TerGatewayData.getTerSyncTimeByMno(this.mno);
            if (syncTime != syncTick) {
                TerTempData terTempData = TerGatewayData.getTerTempDataByMno(this.mno);
                if (null != terTempData) {
                    AConnInfo info = terTempData.getConnInfo();
                    AProtocol protocol = AAutoProtocol.getProtocol(terTempData.protocolName);
                    if (null != protocol && null != info) {
                        String syncValue = TerGatewayData.getTerSyncValueByMno(this.mno);
                        // 获取流水号
                        int serNo = head.getSerNo();
                        // 再尝试构造下行消息
                        final ByteBuf byteBuf = ((WA206DeEnCoder) protocol).builtSyncParamRsp(info, serNo, syncTime, syncValue);
                        // 最后发送下行数据
                        if (byteBuf != null) {
                            info.downMsg(byteBuf);
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("doBusiness", e);
        }
    }

    @Override
    public boolean autoRsp() {
        return false;
    }

    @Override
    public ByteBuf getRsp(AConnInfo info, AProtocol protocol) {
        return ((WA206DeEnCoder) protocol).getSyncParamRsp(info, this);
    }


    @Override
    public String getMachineNO() {
        return this.mno;
    }
}
